package cn.tiny.common.rpc.http;

import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created on 2018/11/20 16:33
 */
public class HttpSender {

    /**
     * Created on 2018/11/20 16:58
     */
    public static String get(String url) {
        if(url == null)
            return null;
        String content = null;
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;

        try {
            response = httpclient.execute(httpGet);
            content = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally{
            try {
                if(httpclient != null)
                    httpclient.close();
                if(response != null)
                    response.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return content;
    }

    /**
     * Created on 2018/11/20 16:37
     */
    public static String post(String url, Map<String, String> paramMap) {
        if(url == null)
            return null;
        return sendHttpPost(buildHttpPost(url, paramMap), null);
    }

    /**
     * Created on 2018/11/20 16:38
     */
    private static HttpPost buildHttpPost(String url, Map<String, String> paramMap) {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(15000).setConnectionRequestTimeout(15000).build());
        if(paramMap == null)
            return httpPost;
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : paramMap.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            nvps.add(new BasicNameValuePair(key, value));
        }
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
        return httpPost;
    }

    /**
     * 发送请求
     */
    private static String sendHttpPost(HttpPost httpPost, Map<String, String> headers){
        CloseableHttpClient httpclient = HttpClients.createDefault();
        if(headers != null)
            httpPost.setHeaders(buildHeader(headers));
        String content = null;
        CloseableHttpResponse response = null;

        try {
            response = httpclient.execute(httpPost);
            content = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally{
            try {
                if(httpclient != null)
                    httpclient.close();
                if(response != null)
                    response.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return content;
    }

    private static Header[] buildHeader(Map<String, String> params) {
        Header[] headers = null;
        if (params != null && params.size() > 0) {
            headers = new BasicHeader[params.size()];
            int i = 0;
            for (Map.Entry<String, String> entry : params.entrySet()) {
                headers[i] = new BasicHeader(entry.getKey(), entry.getValue());
                i++;
            }
        }
        return headers;
    }
}
